import React, { Component } from "react";
import Modal from 'bee-modal';
import 'bee-modal/build/Modal.css';
import Table from "bee-table";
import 'bee-table/build/Table.css';
import multiSelect from "bee-table/build/lib/multiSelect";
import { Button, Checkbox, Radio, Icon, InputGroup, FormControl } from "tinper-bee";
import selfNaxios from 'utils/ajaxConfig.js';
import { vendorsDanger } from 'utils/config.js';
import './index.less'
const MultiSelectTable = multiSelect(Table, Checkbox);
let searchTimer;
class GridRefer extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: true,
            data: [],
            selected: new Map(),
            keyword: '',
        }
    }
    componentDidUpdate(prevProps, prevState, snapshot) {
        let {
            isShow,
            refPk,
            refUrl,
            refMethod = 'get',
            refQueryCondition,
            resultPath,
            selected = '',
            isMultiSelectedEnabled,
        } = this.props;
        if (prevProps.isShow && !isShow) {
            this.setState({
                data: [],
                selected: new Map(),
            });
        }
        if (!prevProps.isShow && isShow) {
            let paramKey = refMethod == 'get' ? 'params' : 'data';
            let selectedKeys = new Map();
            if (!isMultiSelectedEnabled) {
                selected = selected ? [selected] : [];
            } else {
                selected = selected || [];
            }
            selected.forEach(key => {
                if (key) {
                    selectedKeys.set(key, true);
                }
            });
            selfNaxios({
                method: refMethod,
                url: refUrl,
                [paramKey]: typeof refQueryCondition === 'function' ? refQueryCondition.call(this) : null,
            }, (res) => {
                let resData = res.data;
                if (resData.resultCode === 'ok') {
                    let data = resData.result;
                    if (resultPath) {
                        data = data[resultPath];
                    }
                    let initSelected = new Map();
                    if (selectedKeys.size != 0) {
                        data.forEach(cur => {
                            if (selectedKeys.has(cur[refPk])) {
                                cur._checked = true;
                                initSelected.set(cur[refPk], cur);
                            }
                        })
                    }
                    this.setState({
                        data,
                        selected: initSelected,
                    });
                } else {
                    // vendorsDanger({ text: data.exMsg }); //Todo
                }
            }, (error) => {

            })
        }
    }
    onTextSearch = (e) => {
        clearTimeout(searchTimer)
        let keyword = e.target.value;
        searchTimer = setTimeout(() => {
            this.setState({
                keyword,
            })
        }, 300);
    }
    getSelectedDataFunc = (selectedList, record, index, newData) => {
        this.state.selected.clear();
        selectedList.forEach(cur => {
            this.state.selected.set(cur[this.props.refPk], cur);
        })
    };
    setRowClassName = (record, index, indent) => {
        if (this.state.selected.has(record[this.props.refPk])) {
            return 'single-select-row-selected';
        }
    }
    onRowClick = (record, index, e) => {
        let { isMultiSelectedEnabled, refPk } = this.props;
        if (isMultiSelectedEnabled) {
            // record._checked = !record._checked;
            // this.setState(state => {
            //     if (record._checked) {
            //         state.selected.set(record[refPk], record);
            //     } else {
            //         state.selected.delete(record[refPk])
            //     }
            //     return {
            //         selected: state.selected,
            //         data: state.data,
            //     }
            // })
        } else {
            this.state.selected.clear();
            this.state.selected.set(record[refPk], record);
            this.setState({
                selected: this.state.selected,
            })
        }
    }
    onRowDoubleClick = (record, index, e) => {
        let { isMultiSelectedEnabled, refPk } = this.props;
        if (!isMultiSelectedEnabled) {
            this.state.selected.clear();
            this.state.selected.set(record[refPk], record);
            this.setState({
                selected: this.state.selected,
            })
            this.sureClick();
        }
    }
    sureClick = () => {
        let { refPk, fieldDisplayed, fieldValued, isMultiSelectedEnabled } = this.props;
        let display = [], value = [], record;
        Array.from(this.state.selected.keys()).forEach(key => {
            record = this.state.selected.get(key);
            display.push(record[fieldDisplayed]);
            value.push(record[fieldValued]);
        });
        display = display.join(',');
        if (!isMultiSelectedEnabled) {
            value = value.join(',');
        }
        this.props.getSelected(this.props.attrcode, { display, value, record, });
        this.props.closeRefer();
    }
    render() {
        let {
            isMultiSelectedEnabled,
            isShow = false,
            showModal,
            closeRefer,
            label,
            columns,
            refPk,
            filterColumn,
        } = this.props;
        let RenderTable;
        let setRowClassName = {};
        if (isMultiSelectedEnabled) {
            RenderTable = MultiSelectTable;
        } else {
            RenderTable = Table;
            setRowClassName = {
                rowClassName: this.setRowClassName
            }
        }
        let tableData = this.state.data
        let keyword;
        if (this.state.keyword) {
            keyword = this.state.keyword.toLowerCase();
            if (typeof filterColumn === 'string') {
                tableData = tableData.filter(cur => {
                    return cur[filterColumn] && cur[filterColumn].toLowerCase().includes(keyword);
                })
            } else if (Array.isArray(filterColumn)) {
                tableData = tableData.filter(cur => {
                    for (let i = 0; i < filterColumn.length; i++) {
                        if (cur[filterColumn[i]] && cur[filterColumn[i]].toLowerCase().includes(keyword)) {
                            return true;
                        }
                    }
                    return false;
                })
            }
        }
        return (
            <div>
                <Modal className='ygc-grid-refer' show={isShow} size={'lg'} onHide={closeRefer} backdrop={false}>
                    <Modal.Header closeButton>
                        <Modal.Title > {label} </Modal.Title>
                    </Modal.Header >
                    <Modal.Body>
                        {filterColumn &&
                            <InputGroup simple className='u-search-group'>
                                <FormControl
                                    type="text"
                                    onChange={this.onTextSearch}
                                />
                                <InputGroup.Button shape="border">
                                    <span className="uf uf-search"> </span>
                                </InputGroup.Button>
                                {/* <InputGroup.Button>
                                <Button><span className="uf uf-search"> </span></Button>
                            </InputGroup.Button> */}
                            </InputGroup>
                        }
                        <RenderTable
                            emptyText={() => '暂无数据'}
                            bordered
                            columns={columns}
                            scroll={{ y: 520 }}
                            data={tableData}
                            // loading={{ show: this.state.loading }}
                            rowKey={refPk}
                            {...setRowClassName}
                            onRowClick={this.onRowClick}
                            onRowDoubleClick={this.onRowDoubleClick}
                            multiSelectConfig={{
                                inverse: true, //设置选中为红色填充
                            }}
                            getSelectedDataFunc={this.getSelectedDataFunc}
                        />
                    </Modal.Body>
                    <Modal.Footer>
                        <div className="refer-btn-group">
                            <Button className='icon-cancel-btn' onClick={closeRefer}> 取消 </Button>
                            <Button colors="primary" onClick={this.sureClick}> 确认 </Button>
                        </div>
                    </Modal.Footer>
                </Modal>
            </div>
        )
    }
}


export default GridRefer;